import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * @className: ServerThread
 * @description: 服务端线程.服务端处理实现
 * @author: WangXiaosong
 * @date: 2022/6/8
 **/
public class ServerThread extends Thread {
    private Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while (true) {
                //读取从客户端传来的信息
                String mess = bufferedReader.readLine();
                String user = mess.substring(0, mess.indexOf(" "));
                String pwd = mess.substring(mess.indexOf(" ") + 1);

                //检查用户名密码是否正确,并返回相应信息到客户端
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                String info;
                if (login(user, pwd)) {
                    info = "登陆成功!\n";
                } else {
                    info = "用户名或密码错误,请重新输入!\n";
                }
                bufferedWriter.write(info);
                bufferedWriter.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查用户名密码是否正确
     * @param user 用户名
     * @param pwd 密码
     * @return 结果
     */
    private static boolean login(String user, String pwd) {
        String[] users = {"123", "456", "789"};
        String[] pwds = {"321", "654", "987"};

        int indexOfUser = 0;
        boolean result = false;

        for (int i = 0; i < user.length(); i++) {
            if (users[i].equals(user)) {
                indexOfUser = i;
                break;
            }
        }

        if (!users[indexOfUser].equals(user)) {
            return result;
        }

        result = pwds[indexOfUser].equals(pwd);
        return result;
    }
}
